package com.learn.config;

import com.learn.io.Resources;
import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author WuLiangHang
 */
public class XmlMapperBuilder {
    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public XmlMapperBuilder() {
    }

    public void parse(String path) throws DocumentException {
        InputStream input = Resources.getResource(path);
        Document document = new SAXReader().read(input);
        Element root = document.getRootElement();
        String namespace = root.attributeValue("namespace");
        List<Element> selectElements = root.selectNodes("//select");
        for (Element element :
                selectElements) {
            String id = new StringBuilder(namespace).append(".").append(element.attributeValue("id")).toString();
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            MappedStatement statement = new MappedStatement(id, resultType, parameterType, sql);
            configuration.getMap().put(id, statement);
        }
    }
}
